package org.jeecg.modules.wlhy.wlxypt.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.PayConstants;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.ecloud.sdk.util.DateUtil;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNoteDTO;
import org.jeecg.modules.wlhy.shipping.mapper.HyShippingNoteMapper;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.jeecg.modules.wlhy.wlxypt.entity.HyShippingNoteHD;
import org.jeecg.modules.wlhy.wlxypt.entity.HyXlyReport;
import org.jeecg.modules.wlhy.wlxypt.entity.XlyReportDTO;
import org.jeecg.modules.wlhy.wlxypt.mapper.XlyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class XLYService extends ServiceImpl<XlyMapper, HyXlyReport> {

    @Autowired
    private HyShippingNoteMapper hyShippingNoteMapper;

    @Autowired
    private XlyMapper xlyMapper;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    private WlxyptServiceApi wlxyptServiceApi;

    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Autowired
    private RedisUtil redisUtil;


    public void insertOrUpdate(HyShippingNote shippingNode,Result<?> result) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("shipping_id",shippingNode.getId());
        int count = this.count(queryWrapper);

        HyXlyReport report = new HyXlyReport();
        String time = DateUtil.getTime();
        report.setShippingId(shippingNode.getId());
        report.setShippingNoteNumber(shippingNode.getShippingNoteNumber());
        if (result.isSuccess()){
            report.setUploadStatus("1");
        } else {
            report.setUploadStatus("2");
        }
        try {
            report.setCreateBy(UserUtil.getLoginUser().getUsername());
        }catch (Exception e){
            log.error(e.getMessage());
            report.setCreateBy("admin");
        }
        report.setUploadDate(DateUtil.fomatDatetime(time));
        report.setFailureReason(result.getMessage());
        if (count==0){
            this.save(report);
        }else {
            HyXlyReport xlyReport = xlyMapper.getByShippingId(shippingNode.getId());
            xlyReport.setUploadStatus(report.getUploadStatus());
            xlyReport.setFailureReason(result.getMessage());
            this.updateById(xlyReport);
        }
    }

    public IPage<XlyReportDTO> getXinluyunEtcList(Page<XlyReportDTO> page, QueryWrapper<XlyReportDTO> queryWrapper) {
        IPage<XlyReportDTO> pageList = hyShippingNoteMapper.getXlyEtcList(page, queryWrapper);
        for (XlyReportDTO dto : pageList.getRecords()) {
            List<HyShippingNoteBill> shippingNoteBills = hyShippingNoteBillService.list(new LambdaQueryWrapper<HyShippingNoteBill>().eq(HyShippingNoteBill::getShippingId, dto.getId()));
            for (HyShippingNoteBill shippingNoteBill : shippingNoteBills) {
                if (dto.getPayType().equals(PayConstants.PAY_TYPE.BY_PREPAY)&&shippingNoteBill.getBillType().equals("6")){
                    dto.setBillPreNum(shippingNoteBill.getBillNum());
                    dto.setBillPreBankImage(shippingNoteBill.getBankHdImg());
                }else {
                    dto.setBillNum(shippingNoteBill.getBillNum());
                    dto.setBankImage(shippingNoteBill.getBankHdImg());
                }
            }
        }
        return pageList;
    }

    public void deleteByShippingId(String shippingId) {
       HyXlyReport report = xlyMapper.getByShippingId(shippingId);
       if (report!=null){
           xlyMapper.deleteById(report.getId());
       }
    }

    public Result<?> uploadBankHD(@RequestBody HyShippingNoteHD hyShippingNote) {


        List<HyShippingNoteBill> shippingNoteBills = hyShippingNoteBillService.list(new LambdaQueryWrapper<HyShippingNoteBill>().eq(HyShippingNoteBill::getShippingId, hyShippingNote.getId()));
        if (CollUtil.isEmpty(shippingNoteBills)) {
            return Result.error("资金流水不存在");
        }
        String bankHdImg = "";
        for (HyShippingNoteBill shippingNoteBill : shippingNoteBills) {
            if (shippingNoteBill.getBillType().equals("6")){
                bankHdImg = hyShippingNote.getBillPreBankImage();
            }else if(StringUtils.isNotEmpty(hyShippingNote.getBankImage())){
                bankHdImg =  hyShippingNote.getBankImage();
            }else {
                bankHdImg=shippingNoteBill.getBankHdImg();
            }
            shippingNoteBill.setBankHdImg(bankHdImg);
            hyShippingNoteBillService.updateById(shippingNoteBill);
        }
        return Result.ok();

    }

    public Result<?> upload(HyDriver driver, HyVehicle vehicle, List<HyShippingNoteBill> shippingNoteBills, HyShippingNote shippingNote) {
        //登录获取token
        boolean hasKey = redisUtil.hasKey("WSAPIToken");
        String token = null;
        if (hasKey==true){
            token = redisUtil.get("WSAPIToken").toString();
        }else {
            Result<?> LoginResult = wlxyptServiceApi.login();
            if (LoginResult.isSuccess()){
                token = LoginResult.getResult().toString();
            }else {
                return Result.error(LoginResult.getMessage());
            }
        }
        Result getCountOfDriver = wlxyptServiceApi.query(driver.getIdcard(),token);
        //上传司机
        Result<?> driverResult = null;
        if (!getCountOfDriver.isSuccess()){
            try {
                driverResult = wlxyptServiceApi.addDriver(shippingNote,driver, vehicle, token);
                if (!driverResult.isSuccess()){
                    this.insertOrUpdate(shippingNote,driverResult);
                    return Result.error(driverResult.getMessage());
                }
            } catch (IOException e) {
                e.printStackTrace();
                return Result.error("新增司机失败");
            }
        }

        Result<?> queryShippingNoteStatusResult = wlxyptServiceApi.queryShippingNote(shippingNote.getShippingNoteNumber(), token);
        if (!queryShippingNoteStatusResult.isSuccess()){
            //上传运单
            try {
                Result<?> shippingNodeResult = wlxyptServiceApi.addShippingNode(shippingNote, shippingNoteBills, driver, vehicle, token);
                if (!shippingNodeResult.isSuccess()){
                    this.insertOrUpdate(shippingNote,shippingNodeResult);
                    return Result.error(shippingNodeResult.getMessage());
                }else {
                    this.insertOrUpdate(shippingNote,shippingNodeResult);
                    return Result.OK();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("上传运单失败");
            }
        }else {
            //上传运单
            try {
                Result<?> result = wlxyptServiceApi.deleteShippingNode(shippingNote.getShippingNoteNumber(), token);
                if (result.isSuccess()){
                    Result<?> shippingNodeResult = wlxyptServiceApi.addShippingNode(shippingNote, shippingNoteBills, driver, vehicle, token);
                    if (!shippingNodeResult.isSuccess()) {
                        this.insertOrUpdate(shippingNote, shippingNodeResult);
                        return Result.error(shippingNodeResult.getMessage());
                    } else {
                        this.insertOrUpdate(shippingNote, shippingNodeResult);
                    }
                }else {
                    return Result.error("上传运单失败，请重新上传");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("上传运单失败");
            }
        }
        return Result.OK();
    }

    /**
     * 获取导出列表
     * @param queryWrapper
     * @return
     */
    public List<HyShippingNoteDTO> getXlyReportList(QueryWrapper<HyShippingNoteDTO> queryWrapper) {
        return hyShippingNoteMapper.getXlyReportList(queryWrapper);
    }
}
